package com.sun.tag.components;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.apache.commons.lang3.StringUtils;

/**
 * 引入资源的标签
 * TODO 这是一种淘汰的做法,可以直接根据使用的组件初始化引用资源
 * @author SunAFei
 *
 */
public class RefTag extends SimpleTagSupport {
	private String source;
	private final static String THEME_ALERTIFY = "alert";
	private final static String THEME_LAYER = "layer";
	private final static String THEME_ZTREE = "tree";

	@Override
	public void doTag() throws JspException, IOException {
		HttpServletRequest request = (HttpServletRequest) ((PageContext) this.getJspContext()).getRequest();
		String contextPath = request.getContextPath();
		JspWriter out = this.getJspContext().getOut();
		out.write("<!-- " + contextPath + request.getServletPath() + " -->");
		out.write(proSource(contextPath));
		super.doTag();
	}

	private String proSource(String contextPath) {
		StringBuilder sourceBuf = new StringBuilder();
		
		sourceBuf.append("<script src='" + contextPath + "/system/script/jquery-1.11.1.js'></script>");
		sourceBuf.append("<link href='" + contextPath + "/system/css/bootstrap.min.css' rel='stylesheet' type='text/css' media='all'>");
		if (StringUtils.isBlank(source)) {
			return sourceBuf.toString();
		}
		String[] sources = source.split(",");
		for (String sourceStr : sources) {
			if (StringUtils.equals(THEME_ALERTIFY, sourceStr)) {
				sourceBuf.append("<script src='" + contextPath + "/system/script/alertifyjs/alertify.js'></script>")
						.append("<link rel='stylesheet' href='" + contextPath + "/system/script/alertifyjs/css/alertify.css'>");
			} else if (StringUtils.equals(THEME_LAYER, sourceStr)) {
				sourceBuf.append("<script src='" + contextPath + "/system/script/layer/layer.js'></script>").append("<link href='"
						+ contextPath + "/system/script/layer/skin/layer.css' rel='stylesheet' type='text/css' media='all'>");
			} else if (StringUtils.equals(THEME_ZTREE, sourceStr)) {
				sourceBuf.append("<link href=\"" + contextPath + "/system/script/zTree/zTreeStyle/zTreeStyle.css\" rel=\"stylesheet\" type=\"text/css\">\n");
				sourceBuf.append("<script src=\"" + contextPath + "/system/script/zTree/jquery.ztree.all-3.5.min.js\"></script>\n");
				sourceBuf.append("<script src=\"" + contextPath + "/system/script/zTree/jquery.ztree.exhide-3.5.js\"></script>\n");
			}
		}
		return sourceBuf.toString();
	}

	public void setSource(String source) {
		this.source = source;
	}

	/**
	 * 自定义标签，在sun-theme-taglib，可以被页面使用的函数，使用方法“${v:title('Feature list')}
	 * @author SunAFei
	 * @param name 参数
	 * @return
	 */
	public static String showTitle(String name) {
		return name;
	}
}
